package cn.com.cfae.iras.doc.analyze.components.rationality;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import cn.com.cfae.iras.doc.analyze.parse.model.PageModel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

;

/**
 * 内容合理性
 * M-11
 * 检索“XX个工作日内召开债务融资工具持有人会议”中的数字，假设这个数字为A,检索“XX个工作日的宽限期”字段中的数字，
 * 1、涉及投资人保护条款进行该项检查；
 * 2、工作日、宽限期同时出现进行比较；
 * 3、有宽限期，必有持有人会议；
 * 4、有持有人会议，可以没有宽限期；
 * 5、宽限期≤工作日；
 * 6、在页面添加“是否涉及投资人保护条款”选项， 由人工选择是否触发该项检查；
 *
 * 预评/发行阶段
 */
@Component("R1010")
@Scope("prototype")
public class R1010 extends BaseComponent {
    private static Logger log = LoggerFactory.getLogger(R1010.class);
    @Autowired
    private HandingData handingData;
    @Override
    public List<ComponentResult> handlerM() {
        log.info("获取R1010组件M");
        List<ComponentResult> componentResults = checkRulesR1010(getCatalogId(),getCatalogId(), StringUtils.isNotEmpty(getChapterId())?getChapterId():"M-11",getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        log.info("获取R1010组件BM");
        List<ComponentResult> componentResults = checkRulesR1010(getCatalogId(),getCatalogId(),StringUtils.isNotEmpty(getChapterId())?getChapterId():"BM-11",getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        log.info("获取R1010组件DM");
        List<ComponentResult> componentResults = checkRulesR1010(getCatalogId(),getCatalogId(),StringUtils.isNotEmpty(getChapterId())?getChapterId():"DM-10",getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        log.info("获取R1010组件BDM");
        List<ComponentResult> componentResults = checkRulesR1010(getCatalogId(),getCatalogId(),StringUtils.isNotEmpty(getChapterId())?getChapterId():"BDM-10",getRuleTitle());
        return componentResults;
    }

    private List<ComponentResult> checkRulesR1010(String model,String catalogId,String chapterId,String ruleName){

        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;

        int startPageNum = 0;

        boolean cyrFlag = false;
        String cyrRegex = ".*持有人会议.*(中国|上海|交易商).*(认可|网).*";
        int cyrPageNum = 0;
        List<ComponentResult.TextPosition> cyrContentAndPositionList = null;

        boolean kxqFlag = false;
        String kxqRegex = ".*(条触发情形|违反约定事件之后|同意给予发行人|工作日).*((工作日|自然日).*|.*(宽|宽限期)).*";
        int kxqPageNum = 0;
        List<ComponentResult.TextPosition> kxqContentAndPositionList = null;
        boolean isAllSeem = false;
        boolean isAllErr = false;
        boolean isAllRight = false;


        String regexCut = "\\d+|[一二两三四五六七八九十]";
        String regex = "\\d+";
        String cyrContent = null;
        String kxqContent = null;
        List<String> cyrList = new ArrayList<>();
        List<String> kxqList = new ArrayList<>();
        StringBuffer fxrbuf = new StringBuffer();
        StringBuffer kxqbuf = new StringBuffer();

        try {
            if (extractData!=null){
                ChapterModel chapterModel = extractData.getChapterModel(model);
                startPageNum = chapterModel!=null?chapterModel.getStartPage():0;
                if (chapterModel!=null){
                    List<PageModel> pageModelList = chapterModel.getPageModelList();
                    if (CollectionUtils.isNotEmpty(pageModelList)){
                        for (PageModel pageModel :pageModelList){
                           Map<String, Object> containsKeyWord = handingData.isContainsKeyWordOfRegex(pageModel.getJsonTextData(), cyrRegex);
                            cyrFlag = (boolean)containsKeyWord.get("flag");
                            if (cyrFlag){
                                cyrPageNum = pageModel.getPageNumber();
                                cyrContentAndPositionList = (List<ComponentResult.TextPosition>)containsKeyWord.get("position");
                                break;
                            }
                        }
                        cyrPageNum = cyrPageNum!=0?cyrPageNum:startPageNum;
                        for (PageModel pageModel :pageModelList){
                            Map<String, Object> containsKeyWord = handingData.isContainsKeyWordOfRegex(pageModel.getJsonTextData(), kxqRegex);
                            kxqFlag = (boolean)containsKeyWord.get("flag");
                            if (kxqFlag){
                                kxqPageNum = pageModel.getPageNumber();
                                kxqContentAndPositionList = (List<ComponentResult.TextPosition>)containsKeyWord.get("position");
                                break;
                            }
                        }
                        kxqPageNum = kxqPageNum!=0?kxqPageNum:startPageNum;
                    }
                }
            }
            //持有人
            Pattern pattern = Pattern.compile(regexCut);
            Matcher matcher = null;
            if (cyrFlag){
                if (CollectionUtils.isNotEmpty(cyrContentAndPositionList)){
                    for (ComponentResult.TextPosition textPosition : cyrContentAndPositionList){
                        cyrContent= textPosition.getContent();
                    }
                }
                if (StringUtils.isNotEmpty(cyrContent)){
                    matcher = pattern.matcher(cyrContent);
                    while(matcher.find()) {
                        cyrList.add(matcher.group());
                    }
                }
                if (CollectionUtils.isNotEmpty(cyrList)){
                    String cyrTemp = null;
                    if (cyrList.size()>0&&cyrList.size()<=1){
                        cyrTemp =  cyrList.get(0);
                    }else if (cyrList.size()>=2){
                        cyrTemp = cyrList.get(cyrList.size()-1);
                    }
                    cyrContent = cyrTemp;
                }
                Integer fxrInt = formatDate(cyrContent);
                fxrbuf.append(fxrInt);
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"工作日检查-持有人会议:"+cyrContent+"个工作日","已抽取",false,getRegulationId(), cyrPageNum,cyrContentAndPositionList,"01");
                componentResults.add(componentResult);
            }else {
                isAllSeem = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"工作日检查-持有人会议","未抽取到,建议人工核对",true,getRegulationId(), cyrPageNum,cyrContentAndPositionList,"03");
                componentResults.add(componentResult);
            }

            //宽限期
            if (kxqFlag){
                if (CollectionUtils.isNotEmpty(kxqContentAndPositionList)){
                    for (ComponentResult.TextPosition textPosition : kxqContentAndPositionList){
                        kxqContent= textPosition.getContent();
                    }
                }
                if (StringUtils.isNotEmpty(kxqContent)){
                    matcher = pattern.matcher(kxqContent);
                    while(matcher.find()) {
                        kxqList.add(matcher.group());
                    }
                }
                if (CollectionUtils.isNotEmpty(kxqList)){
                    String tempStr = null;
                    if (kxqList.size()>0&&kxqList.size()<=1){
                        tempStr =  kxqList.get(0);
                    }else if (kxqList.size()>=2){
                        tempStr = kxqList.get(kxqList.size()-1);
                    }
                    kxqContent = tempStr;
                }
                Integer kxqInt = formatDate(kxqContent);
                kxqbuf.append(kxqInt);
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"工作日检查-宽限期:"+kxqContent+"个工作日","已抽取",false,getRegulationId(), kxqPageNum,kxqContentAndPositionList,"01");
                componentResults.add(componentResult);
            }else {
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"工作日检查-宽限期","未抽取到,建议人工核对",true,getRegulationId(), kxqPageNum,kxqContentAndPositionList,"03");
                componentResults.add(componentResult);
            }

            if (cyrFlag&&kxqFlag){

                if (StringUtils.isNotEmpty(fxrbuf.toString())&&StringUtils.isNotEmpty(kxqbuf.toString())){
                    int fxrInt = Integer.parseInt(fxrbuf.toString());
                    int kxqInt = Integer.parseInt(kxqbuf.toString());
                    if (kxqInt<=fxrInt){
                        isAllRight = true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"持有人会议与宽限期工作日检查","合理",false,getRegulationId(), cyrPageNum,cyrContentAndPositionList,"01");
                        componentResults.add(componentResult);
                    }else {
                        isAllErr = true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"持有人会议与宽限期工作日检查","该文档内容披露不合理",true,getRegulationId(), cyrPageNum,cyrContentAndPositionList,"02");
                        componentResults.add(componentResult);
                    }
                }else {
                    isAllSeem =true;
                    componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"持有人会议与宽限期工作日检查","未识别,建议人工核对",true,getRegulationId(), startPageNum,cyrContentAndPositionList,"03");
                    componentResults.add(componentResult);
                }

            }else if (!cyrFlag&&kxqFlag){
                isAllErr =true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"持有人会议与宽限期工作日检查","持有人会议日缺失,建议人工核对",true,getRegulationId(), startPageNum,cyrContentAndPositionList,"02");
                componentResults.add(componentResult);
            }else if (cyrFlag&&!kxqFlag){
                isAllRight = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"持有人会议与宽限期工作日检查","合理",false,getRegulationId(), cyrPageNum,cyrContentAndPositionList,"01");
                componentResults.add(componentResult);
            }else {
                isAllSeem = true;
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"持有人会议与宽限期工作日检查","未识别,建议人工核对",true,getRegulationId(), startPageNum,cyrContentAndPositionList,"03");
                componentResults.add(componentResult);
            }

            if (isAllErr){
                for (ComponentResult result:componentResults){
                    result.setExist("02");
                }
            }
            if (isAllRight){
                for (ComponentResult result:componentResults){
                    result.setExist("01");
                }
            }
            if (isAllSeem){
                for (ComponentResult result:componentResults){
                    result.setExist("03");
                }
            }


        }catch (Exception e){
            componentResults.clear();
            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"持有人会议与宽限期工作日检查","未识别,建议人工核对",true,getRegulationId(), startPageNum,cyrContentAndPositionList,"03");
            componentResults.add(componentResult);
            log.error(e.getMessage(),e);
        }
        return  componentResults;
    }


    private Integer formatDate(String dateString){
        if (StringUtils.isEmpty(dateString)){
            return null;
        }
        switch (dateString){
            case "零":
                return 0;
            case "一":
                return 1;
            case "二":
                return 2;
            case "两":
                return 2;
            case "三":
                return 3;
            case "四":
                return 4;
            case "五":
                return 5;
            case "六":
                return 6;
            case "七":
                return 7;
            case "八":
                return 8;
            case "九":
                return 9;
            case "十":
                return 10;
                default:
                    return Integer.parseInt(dateString);
        }
    }
}
